package co.baiku.boot.job.service.impl;

import co.baiku.boot.common.type.TimeFormat;
import co.baiku.boot.common.validate.Validation;
import co.baiku.boot.job.model.QuartzJobInfo;
import co.baiku.boot.job.service.QuartzJobService;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class QuartzJobServiceImpl implements QuartzJobService {
    private Logger logger = LoggerFactory.getLogger(QuartzJobServiceImpl.class);
    @Resource
    private Scheduler scheduler;

    /**
     * 所有任务列表
     */
    @Override
    public List<QuartzJobInfo> list() {
        List<QuartzJobInfo> list = new ArrayList<>();
        try {
            for (String groupJob : scheduler.getJobGroupNames()) {
                for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.groupEquals(groupJob))) {
                    List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
                    for (Trigger trigger : triggers) {
                        Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
                        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
                        String cronExpression = "", createTime = "";
                        if (trigger instanceof CronTrigger) {
                            CronTrigger cronTrigger = (CronTrigger) trigger;
                            cronExpression = cronTrigger.getCronExpression();
                            createTime = cronTrigger.getDescription();
                        }
                        QuartzJobInfo info = new QuartzJobInfo();
                        info.setJobName(jobKey.getName());
                        info.setJobGroup(jobKey.getGroup());
                        info.setJobDescription(jobDetail.getDescription());
                        info.setJobStatus(triggerState.name());
                        info.setCronExpression(cronExpression);
                        info.setCreateTime(createTime);
                        list.add(info);
                    }
                }
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        return list;
    }

    /**
     * 保存定时任务
     *
     * @param info
     */
    @SuppressWarnings("unchecked")
    @Override
    public void addJob(QuartzJobInfo info) {
        String jobName = info.getJobName(),
                jobGroup = info.getJobGroup(),
                cronExpression = info.getCronExpression(),
                jobDescription = info.getJobDescription(),
                createTime = info.getCreateTime()==null?TimeFormat.toStr(LocalDateTime.now(),TimeFormat.DATETIME):info.getCreateTime();
        try {
            if (checkExists(jobName, jobGroup)) {
                logger.info("add job fail, job already exist, jobGroup:{}, jobName:{}", jobGroup, jobName);
            }
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
            JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
            CronScheduleBuilder schedBuilder = CronScheduleBuilder.cronSchedule(cronExpression).withMisfireHandlingInstructionDoNothing();
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withDescription(createTime).withSchedule(schedBuilder).build();
            Class<? extends Job> clazz = (Class<? extends Job>) Class.forName(jobName);
            JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(jobKey).withDescription(jobDescription).build();
            if(info.getJobDataMap()!=null && info.getJobDataMap().size()>0){
                jobDetail.getJobDataMap().putAll(info.getJobDataMap());
            }
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (ClassNotFoundException e) {
            logger.error("类名不存在", e);
            throw Validation.error("任务类不存在:" + jobName);
        } catch (Exception e) {
            if (e instanceof ParseException) {
                logger.error("执行表达式错误,exception:{}", e.getMessage());
                throw Validation.error("执行表达式错误:" + cronExpression);
            } else {
                logger.error("任务添加失败", e);
                throw Validation.error("任务添加失败:" + e.getMessage());
            }
        }
    }

    /**
     * 修改定时任务
     *
     * @param info
     */
    @Override
    public boolean edit(QuartzJobInfo info) {
        String jobName = info.getJobName(),
                jobGroup = info.getJobGroup(),
                cronExpression = info.getCronExpression(),
                jobDescription = info.getJobDescription(),
                createTime = TimeFormat.toStr(LocalDateTime.now(), TimeFormat.DATETIME);
        try {
            if (!checkExists(jobName, jobGroup)) {
                logger.info("edit job fail, job is not exist, jobGroup:{}, jobName:{}", jobGroup, jobName);
            }
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
            JobKey jobKey = new JobKey(jobName, jobGroup);
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression).withMisfireHandlingInstructionDoNothing();
            CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withDescription(createTime).withSchedule(cronScheduleBuilder).build();

            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            jobDetail.getJobBuilder().withDescription(jobDescription).build();
            if(info.getJobDataMap()!=null && info.getJobDataMap().size()>0){
                jobDetail.getJobDataMap().clear();
                jobDetail.getJobDataMap().putAll(info.getJobDataMap());
            }
            Set<Trigger> triggerSet = new HashSet<>();
            triggerSet.add(cronTrigger);

            scheduler.scheduleJob(jobDetail, triggerSet, true);
            return true;
        } catch (SchedulerException e) {
            logger.error("类名不存在或执行表达式错误,exception:{}", e.getMessage());
        }
        return false;
    }

    /**
     * 删除定时任务
     *
     * @param jobName
     * @param jobGroup
     */
    @Override
    public boolean delete(String jobName, String jobGroup) {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
        try {
            if (checkExists(jobName, jobGroup)) {
                scheduler.pauseTrigger(triggerKey);
                scheduler.unscheduleJob(triggerKey);
                logger.info("delete job, triggerKey:{},jobGroup:{}, jobName:{}", triggerKey, jobGroup, jobName);
                return true;
            }
        } catch (SchedulerException e) {
            logger.error(e.getMessage());
        }
        return false;
    }

    /**
     * 暂停定时任务
     *
     * @param jobName
     * @param jobGroup
     */
    @Override
    public boolean pause(String jobName, String jobGroup) {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
        try {
            if (checkExists(jobName, jobGroup)) {
                scheduler.pauseTrigger(triggerKey);
                logger.info("pause job success, triggerKey:{},jobGroup:{}, jobName:{}", triggerKey, jobGroup, jobName);
                return true;
            }
        } catch (SchedulerException e) {
            logger.error(e.getMessage());
        }
        return false;
    }

    /**
     * 重新开始任务
     *
     * @param jobName
     * @param jobGroup
     */
    @Override
    public boolean resume(String jobName, String jobGroup) {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);

        try {
            if (checkExists(jobName, jobGroup)) {
                scheduler.resumeTrigger(triggerKey);
                logger.info("resume job success,triggerKey:{},jobGroup:{}, jobName:{}", triggerKey, jobGroup, jobName);
                return true;
            }
        } catch (SchedulerException e) {
            logger.error(e.getMessage());
        }
        return false;
    }

    /**
     * 立即执行任务
     *
     * @param jobName
     * @param jobGroup
     */
    @Override
    public boolean trigger(String jobName, String jobGroup) {
        JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
        try {
            if (checkExists(jobName, jobGroup)) {
                scheduler.triggerJob(jobKey);
                logger.info("trigger job success,jobKey:{}", jobKey);
                return true;
            }
        } catch (SchedulerException e) {
            logger.error(e.getMessage());
        }
        return false;
    }

    /**
     * 验证是否存在
     *
     * @param jobName
     * @param jobGroup
     * @throws SchedulerException
     */
    @Override
    public boolean checkExists(String jobName, String jobGroup) throws SchedulerException {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
        return scheduler.checkExists(triggerKey);
    }
}
